#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations

import os
from typing import Any
import yaml
from ruamel.yaml import YAML

from autoapi.common.base_file_handler import BaseFileHandler
from autoapi.common.log import log
from autoapi.core.path_conf import autoapi_path
from autoapi.utils.time_control import get_current_time


class YamlHandler(BaseFileHandler):
    """YAML文件处理器"""
    
    @staticmethod
    def _load(file_obj, **kwargs) -> Any:
        """从文件对象加载YAML数据"""
        kwargs.setdefault('Loader', yaml.FullLoader)
        return yaml.load(file_obj, **kwargs)

    @staticmethod
    def _dump(data: Any, file_obj, **kwargs) -> None:
        """将数据写入YAML文件对象"""
        kwargs.setdefault('allow_unicode', True)
        yaml.dump(data, file_obj, **kwargs)


def read_yaml(filepath: str, filename: str | None = None) -> dict[str, Any]:
    """
    读取 yaml 文件

    :param filepath: 文件路径
    :param filename: 文件名
    :return: YAML数据
    """
    return YamlHandler.read_file(filepath, filename)


def write_yaml(
    filepath: str,
    filename: str,
    data: Any = None,
    *,
    encoding: str = "utf-8",
    mode: str = "a",
) -> None:
    """
    将数据写入包含 yaml 格式数据的文件

    :param filepath: 文件路径
    :param filename: 文件名
    :param data: 数据
    :param encoding: 文件内容编码格式
    :param mode: 文件写入模式
    :return:
    """
    YamlHandler.write_file(filepath, filename, data, encoding=encoding, mode=mode)


def write_yaml_report(
    filename: str = f'APITestResult_{get_current_time("%Y-%m-%d %H_%M_%S")}.yaml',
    *,
    data: Any,
    encoding: str = "utf-8",
    mode: str = "a",
) -> None:
    """
    写入 yaml 测试报告

    :param filename: 测试报告文件名
    :param data: 写入数据
    :param encoding: 文件编码格式
    :param mode: 文件写入模式
    :return
    """
    _yaml_report_path = autoapi_path.yaml_report_dir
    if not os.path.exists(_yaml_report_path):
        os.makedirs(_yaml_report_path)
    _file = os.path.join(_yaml_report_path, filename)
    try:
        with open(_file, encoding=encoding, mode=mode) as f:
            yaml.dump(data, f, allow_unicode=True)
    except Exception as e:
        log.error(f"写入 {filename} 测试报告失败: {e}")
        raise e
    else:
        log.info(f"🍵 写入测试报告成功: {filename}")


def write_yaml_vars(data: dict) -> None:
    """
    写入 yaml 全局变量

    :param data:
    :return:
    """
    _file = os.path.join(autoapi_path.global_var_dir, "global_vars.yaml")
    try:
        _yaml = YAML()
        with open(_file, encoding="utf-8", mode="r") as f:
            _vars = _yaml.load(f)
            _vars.update(data)
        with open(_file, encoding="utf-8", mode="w") as f:
            _yaml.dump(_vars, f)
    except Exception as e:
        log.error(f"写入 global_vars.yaml 全局变量 {data} 错误: {e}")
    else:
        log.info(f"写入全局变量成功: global_vars.yaml -> {data}")
